<?php

namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\AgentConfig;
use Cache;

class VerifyCodeService
{
    /** @var SmsService */
    private $smsService;

    /** @var XunChengService */
    private $xcService;

    /**
     * VerifyCodeService constructor.
     */
    public function __construct(SmsService $smsService, XunChengService $xunChengService)
    {
        $this->smsService = $smsService;
        $this->xcService = $xunChengService;
    }

    public function send($mobile)
    {
        $code = rand(100000, 999999);
        Cache::set($this->getVerifyCodeCacheKey($mobile), $code);

        $agentId = request()->agent_id;

        try {
            /** @var AgentConfig $smsProvider */
            $smsProvider = AgentConfig::query()->where('agent_id', $agentId)->where('config_key', AgentConfig::SMS_PROVIDER)->first();
            if ($smsProvider && 'xuncheng' === $smsProvider->config_value) {
                $this->xcService->setAgentId($agentId);
                $this->xcService->sendVerifyCode($mobile, $code);
            } else {
                $this->smsService->sendVerifyCode($agentId, $mobile, $code);
            }
        } catch (\Exception $e) {
            throw new ApiException($e->getMessage());
        }
    }

    public function check($mobile, $verifyCode)
    {
        if (config('app.debug') && '8888' == $verifyCode) {
            return;
        }
        $cacheKey = $this->getVerifyCodeCacheKey($mobile);
        $cacheCode = Cache::get($cacheKey);
        if ($cacheCode != $verifyCode) {
            throw new ApiException('验证码错误');
        }
        Cache::delete($cacheKey);
    }

    private function getVerifyCodeCacheKey($mobile)
    {
        return 'verify_code_' . $mobile;
    }
}
